﻿
Imports osi.root.connector
Imports osi.root.delegates
Imports osi.root.envs

Public Module _sleep_wait
    'should not use this, for test only
    Private Function select_sleep_ms() As Int64
        Try
            Dim tc As Int32 = 0
            tc = current_process.Threads().Count()
            If tc > 40 Then
                Return sixteen_timeslice_length_ms
            ElseIf tc > 30 Then
                Return eight_timeslice_length_ms
            ElseIf tc > 20 Then
                Return four_timeslice_length_ms
            ElseIf tc > 10 Then
                Return two_timeslice_length_ms
            Else
                Return timeslice_length_ms
            End If
        Catch
            Return timeslice_length_ms
        End Try
    End Function

    Public Sub timeslice_sleep_wait_when(Of T)(ByVal d As _do(Of T, Boolean), ByRef i As T)
        sleep_wait_when(d, i, select_sleep_ms())
    End Sub

    Public Function timeslice_sleep_wait_when(Of T)(ByVal d As _do(Of T, Boolean),
                                                    ByRef i As T,
                                                    ByVal timeout_ms As Int64) As Boolean
        Return sleep_wait_when(d, i, select_sleep_ms(), timeout_ms)
    End Function

    Public Sub timeslice_sleep_wait_until(Of T)(ByVal d As _do(Of T, Boolean), ByRef i As T)
        sleep_wait_until(d, i, select_sleep_ms())
    End Sub

    Public Function timeslice_sleep_wait_until(Of T)(ByVal d As _do(Of T, Boolean),
                                                     ByRef i As T,
                                                     ByVal timeout_ms As Int64) As Boolean
        Return sleep_wait_until(d, i, select_sleep_ms(), timeout_ms)
    End Function

    Public Sub timeslice_sleep_wait_when(ByVal d As _do(Of Boolean))
        sleep_wait_when(d, select_sleep_ms())
    End Sub

    Public Function timeslice_sleep_wait_when(ByVal d As _do(Of Boolean), ByVal timeout_ms As Int64) As Boolean
        Return sleep_wait_when(d, select_sleep_ms(), timeout_ms)
    End Function

    Public Sub timeslice_sleep_wait_until(ByVal d As _do(Of Boolean))
        sleep_wait_until(d, select_sleep_ms())
    End Sub

    Public Function timeslice_sleep_wait_until(ByVal d As _do(Of Boolean), ByVal timeout_ms As Int64) As Boolean
        Return sleep_wait_until(d, select_sleep_ms(), timeout_ms)
    End Function
End Module
